"""
认证管理API路由
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, Query, Request, status
from fastapi.security import HTTPBearer

from app.schemas.auth import (
    UserCreate, UserUpdate, UserResponse, UserLogin, UserChangePassword,
    LoginResponse, UserListResponse, Token
)
from app.schemas.base import ResponseModel
from app.services.auth_service import AuthService
from app.utils.dependencies import get_current_user, get_current_superuser
from app.models.user import User

router = APIRouter(prefix="/auth", tags=["认证管理"])
security = HTTPBearer()


@router.post(
    "/register",
    response_model=UserResponse,
    status_code=status.HTTP_201_CREATED,
    summary="用户注册"
)
async def register(
    user_data: UserCreate,
    current_user: User = Depends(get_current_superuser)
):
    """用户注册（仅超级用户可操作）"""
    return await AuthService.create_user(user_data)


@router.post(
    "/login",
    response_model=LoginResponse,
    summary="用户登录"
)
async def login(login_data: UserLogin, request: Request):
    """用户登录"""
    return await AuthService.login(login_data, request)


@router.post(
    "/logout",
    response_model=ResponseModel,
    summary="用户登出"
)
async def logout(
    current_user: User = Depends(get_current_user),
    session_token: Optional[str] = None
):
    """用户登出"""
    success = await AuthService.logout(current_user, session_token)
    return ResponseModel(
        success=success,
        message="登出成功" if success else "登出失败"
    )


@router.post(
    "/change-password",
    response_model=ResponseModel,
    summary="修改密码"
)
async def change_password(
    password_data: UserChangePassword,
    current_user: User = Depends(get_current_user)
):
    """修改密码"""
    success = await AuthService.change_password(current_user, password_data)
    return ResponseModel(
        success=success,
        message="密码修改成功" if success else "密码修改失败"
    )


@router.get(
    "/me",
    response_model=UserResponse,
    summary="获取当前用户信息"
)
async def get_current_user_info(current_user: User = Depends(get_current_user)):
    """获取当前用户信息"""
    return UserResponse.from_orm(current_user)


@router.put(
    "/me",
    response_model=UserResponse,
    summary="更新当前用户信息"
)
async def update_current_user(
    user_data: UserUpdate,
    current_user: User = Depends(get_current_user)
):
    """更新当前用户信息"""
    return await AuthService.update_user(current_user.id, user_data)


@router.get(
    "/users/{user_id}",
    response_model=UserResponse,
    summary="获取用户详情"
)
async def get_user(
    user_id: int,
    current_user: User = Depends(get_current_user)
):
    """获取用户详情"""
    return await AuthService.get_user(user_id)


@router.put(
    "/users/{user_id}",
    response_model=UserResponse,
    summary="更新用户"
)
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    current_user: User = Depends(get_current_superuser)
):
    """更新用户（仅超级用户可操作）"""
    return await AuthService.update_user(user_id, user_data)


@router.delete(
    "/users/{user_id}",
    response_model=ResponseModel,
    summary="删除用户"
)
async def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_superuser)
):
    """删除用户（仅超级用户可操作）"""
    success = await AuthService.delete_user(user_id)
    return ResponseModel(
        success=success,
        message="用户删除成功" if success else "用户删除失败"
    )


@router.get(
    "/users",
    response_model=UserListResponse,
    summary="获取用户列表"
)
async def list_users(
    page: int = Query(default=1, ge=1, description="页码"),
    size: int = Query(default=20, ge=1, le=100, description="每页数量"),
    is_active: Optional[bool] = Query(default=None, description="是否激活"),
    search: Optional[str] = Query(default=None, description="搜索关键词"),
    current_user: User = Depends(get_current_user)
):
    """获取用户列表"""
    users, total = await AuthService.list_users(
        page=page,
        size=size,
        is_active=is_active,
        search=search
    )
    
    pages = (total + size - 1) // size
    
    return UserListResponse(
        items=users,
        total=total,
        page=page,
        size=size,
        pages=pages
    )


@router.get(
    "/verify-token",
    response_model=UserResponse,
    summary="验证令牌"
)
async def verify_token(current_user: User = Depends(get_current_user)):
    """验证令牌有效性"""
    return UserResponse.from_orm(current_user)


@router.get(
    "/sessions",
    summary="获取用户会话列表"
)
async def get_user_sessions(
    current_user: User = Depends(get_current_user)
):
    """获取当前用户的会话列表"""
    from app.models.user import UserSession
    
    try:
        sessions = await UserSession.filter(
            user=current_user,
            is_valid=True
        ).order_by("-created_at")
        
        session_list = []
        for session in sessions:
            session_list.append({
                "id": session.id,
                "ip_address": session.ip_address,
                "user_agent": session.user_agent,
                "created_at": session.created_at,
                "expires_at": session.expires_at,
                "is_current": False  # 这里可以根据当前请求的session_token判断
            })
        
        return {
            "sessions": session_list,
            "total": len(session_list)
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取会话列表失败"
        )


@router.delete(
    "/sessions/{session_id}",
    response_model=ResponseModel,
    summary="删除会话"
)
async def delete_session(
    session_id: int,
    current_user: User = Depends(get_current_user)
):
    """删除指定会话"""
    from app.models.user import UserSession
    
    try:
        session = await UserSession.get_or_none(
            id=session_id,
            user=current_user,
            is_valid=True
        )
        
        if not session:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="会话不存在"
            )
        
        session.is_valid = False
        await session.save()
        
        return ResponseModel(
            success=True,
            message="会话删除成功"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除会话失败"
        )


@router.get(
    "/statistics/summary",
    summary="获取认证统计摘要"
)
async def get_auth_statistics(
    current_user: User = Depends(get_current_superuser)
):
    """获取认证统计摘要（仅超级用户可查看）"""
    from app.models.user import User, UserSession
    from datetime import datetime, timedelta
    
    try:
        # 总用户数
        total_users = await User.all().count()
        active_users = await User.filter(is_active=True).count()
        inactive_users = await User.filter(is_active=False).count()
        
        # 超级用户和员工统计
        superusers = await User.filter(is_superuser=True).count()
        staff_users = await User.filter(is_staff=True).count()
        
        # 会话统计
        total_sessions = await UserSession.all().count()
        active_sessions = await UserSession.filter(is_valid=True).count()
        
        # 最近登录统计
        now = datetime.now()
        last_24h = now - timedelta(hours=24)
        last_7d = now - timedelta(days=7)
        last_30d = now - timedelta(days=30)
        
        logins_24h = await User.filter(last_login__gte=last_24h).count()
        logins_7d = await User.filter(last_login__gte=last_7d).count()
        logins_30d = await User.filter(last_login__gte=last_30d).count()
        
        return {
            "user_statistics": {
                "total": total_users,
                "active": active_users,
                "inactive": inactive_users,
                "superusers": superusers,
                "staff": staff_users
            },
            "session_statistics": {
                "total": total_sessions,
                "active": active_sessions
            },
            "login_statistics": {
                "last_24_hours": logins_24h,
                "last_7_days": logins_7d,
                "last_30_days": logins_30d
            }
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取统计数据失败"
        )
